#region using

using System;
//using System.Web;
using System.Text;
using System.Text.RegularExpressions;
//using System.Web.UI;
//using System.Web.UI.HtmlControls;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;

#endregion

/// <summary>
/// base class for simple processing tags that use regex matches in page and post serving
/// </summary>
public abstract class RegexMatchBase
{
    /// <summary>
    /// Hooks up an event handler to the Post.Serving and Page.Serving events.
    /// </summary>
    public RegexMatchBase()
    {
        BlogEngine.Core.Page.Serving += new EventHandler<ServingEventArgs>(Serving);
        BlogEngine.Core.Post.Serving += new EventHandler<ServingEventArgs>(Serving);
    }

    private Regex _Regex;

    protected Regex Regex
    {
        get { return _Regex; }
        set { _Regex = value; }
    }

    /// <summary>
    /// Handles the Page and Post Serving event to take care of the keyword.
    /// </summary>
    private void Serving(object sender, ServingEventArgs e)
    {
        int currentPosition = 0;
        MatchCollection myMatches = Regex.Matches(e.Body);
        StringBuilder sb = new StringBuilder();

        foreach (Match myMatch in myMatches)
        {
            //copy body from current position to start of token into new string 
            if (myMatch.Index > currentPosition)
            {
                sb.Append(e.Body.Substring(currentPosition, myMatch.Index - currentPosition));
            }

            sb.Append(MatchCore(myMatch));

            //move the position on by the length of the 
            currentPosition = myMatch.Index + myMatch.Groups[0].Length;
        }

        //Finally we add any trailing body text.
        sb.Append(e.Body.Substring(currentPosition, e.Body.Length - currentPosition));

        //replace the body text with the embedded list
        e.Body = sb.ToString();

        MatchingComplete(e);
    }

    protected abstract string MatchCore(Match match);
    protected virtual void MatchingComplete(ServingEventArgs e) {}
}
